// import { decipherGcm, queryTrade } from "../../utils/pay/wxpay";
import { decryptAesGcm } from "../../utils/pay/wxpay-partner";
import { api } from "./api";
import { onOrderLogDone } from "./order-log";

export async function onPartnerNotify(body) {
  const { resource } = body;
  if (!resource) {
    throw "缺少参数resource";
  }
  const trade = await decryptAesGcm(resource);
  if (body.event_type == "REFUND.SUCCESS") {
    updateRefund(trade);
  } else if (body.event_type == "TRANSACTION.SUCCESS") {
    return updateTrade(trade);
  }
}

async function updateRefund(trade) {
  const done = trade.refund_status == "SUCCESS";
  const row = await api.getOrder({
    order_no: trade.out_trade_no,
  });
  if (!row) {
    throw "未找到订单";
  }
  await api.postOrder({
    id: row.id,
    pay_info: {
      ...row.pay_info,
      refund_id: trade.refund_id,
      payer_refund: trade.amount.payer_refund,
    },
    status: done ? 7 : 1,
    paid: !done,
  });
  api.postActLog({
    path: "refund",
    act: "wxpay-" + trade.out_trade_no + "-" + trade.refund_status,
    extra: {
      account: trade.user_received_account,
    },
    userId: row.userId,
  });
  return {
    done,
  };
}

async function updateTrade(trade) {
  const order_no = trade.out_trade_no;
  const done = trade.trade_state == "SUCCESS";
  if (done) {
    const pay_info = {
      trans_id: trade.transaction_id,
      payer_total: trade.amount?.payer_total,
      currency: trade.amount?.payer_currency,
    };
    if (/_/.test(order_no)) {
      // 超时费用
      console.log(trade);
      await onOrderLogDone(
        {
          ord_no: order_no,
        },
        pay_info
      );
    } else {
      await onOrderDone(order_no, pay_info);
    }
  }
  api.postActLog({
    path: "pay",
    act: "wxpay-" + order_no + "-" + trade.trade_state,
    extra: {
      desc: trade.trade_state_desc,
      type: trade.bank_type,
    },
    userId: trade.scene_info?.device_id,
  });
  return {
    done,
    order_no,
  };
}

async function onOrderDone(order_no, pay_info) {
  const row = await api.getOrder({
    order_no,
  });
  if (!row) {
    throw "未找到订单";
  }
  if (row.status > 0) {
    return;
  }
  const body = {
    id: row.id,
    status: 1,
    paid: true,
    pay_info,
    payAt: Date.now(),
  };
  const { days } = row.buy_info || {};
  if (days > 0) {
    body.endAt = body.payAt + days * 86400e3;
  }
  await api.postOrder(body);
  await api.postGoods({
    id: row.buy_id,
    sell_num: "_add" + row.count,
  });
}

// 直连商户
export async function onPayNotify(body) {
  const trade = await decipherGcm(body.resource);
  return updateTrade(trade);
}

// 主动查询：增加了服务器负担，暂无必要，onPayNotify被动查询就够了
export async function queryPay(order_no) {
  const trade = await queryTrade({ out_trade_no: order_no });
  // return updateTrade(trade);
  return trade;
}

/* partner notify
{
  id: '54628c13-823c-5658-833f-f4ce7fb55c79',
  create_time: '2024-07-23T14:42:28+08:00',
  resource_type: 'encrypt-resource',
  event_type: 'TRANSACTION.SUCCESS',
  summary: '支付成功',
  resource: {
    original_type: 'transaction',
    algorithm: 'AEAD_AES_256_GCM',
    ciphertext: '2jHDC4S5TCwItUWp2O+66/8BeKEWgXHCiG1uxLWvEHfxlV09cIVJGLoxPXt2oDxFpq23oqSEl0BPP5V51plKTbeSMGv0cAm3n98NQtHVxb7c1OKGlxBEsK9+4pmd2dBI2DMyW6QjDzMivJbnbRDufhDu+nXSWhf51tsW+f67/iyi68RNavN0YqkoBcu+YgFNVj+iEMU6ERsAe5rRvDAe9zSA02wRyQhIGhMOKr8H54u8Df44EmxZrQHrm0dH9G+8ZtzdvMvxvX87DGkz4gt3q6G4wSqaC5nm/6KjZsFWpwMxs1ZkVEo2rxLRUpcN/Z/e/Mn/muv5s8LBW45dXZEHadtwOTa/nXxpYOVuaje2hBRB4q8Y9NcHKPC0qS4REFueAdd75YR28SkfwS1FkKxKMOEIHcuEDRtYO9CqTswAvJPuAfdJ2ueclLGgzYxcJOR7UYZpYyGMZkDBOuLZYxHc2ixdSlGVMaY4N6o/1MJGKJpyh1pUR0OgDWxa4kkFjL6YYOn9o5w77/kIh92JpDbIPED7Lyy5ysPsrf4XVkP6QdssEwEac8eIEzsomjL+Kcf2UOmptWuxWE/BIDehDgV6LQcsVM2GA1KnQAscQ7fyl73M9no8X3LIuowxrT4kul7axmGVJPPIfFj12PJSY5Dens2znaqFcHmvBi9FANxLhxKtIuRu/ZTPWVkSW65vWszuQdNMpZClSpy6QyStWed7hKrdT7Lw9gZQWJWi3N1eYK4V4mrmWOgYk6QkD7I9GHeuyg==',
    associated_data: 'transaction',
    nonce: 'dpI1wOIYrk4Q'
  }
}

{"sp_mchid":"1681597204","sub_mchid":"1681798615","sp_appid":"wxbee7411c145aff51","sub_appid":"wxbee7411c145aff51","out_trade_no":"202407231455168645","transaction_id":"4200002330202407232728254851","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"","success_time":"2024-07-23T14:55:21+08:00","payer":{"sp_openid":"oQq3B6778hZiA0ebmvU4TQiZ9DS8","sub_openid":"oQq3B6778hZiA0ebmvU4TQiZ9DS8"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"},"scene_info":{"device_id":"7"}}
*/
